package sdk.webview.fmc.com.fmcsdk.util;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ImageCompressor {
    private Context context;

    public ImageCompressor(Context context) {
        this.context = context.getApplicationContext();
    }

    /**
     * Compress the image file in place.
     *
     * @param imagePath The path of the image to compress.
     * @param listener  A listener for success and failure callbacks.
     */
    public void compressImageInPlace(String imagePath, OnCompressListener listener) {
        if (listener == null) throw new IllegalArgumentException("Listener cannot be null");

        File originalImageFile = new File(imagePath);

        // Create a temporary directory to save the compressed process files
        File tempDir = new File(context.getCacheDir(), "temp");
        tempDir.mkdirs();

        // Use Luban to compress the image to a temporary file
        Luban.with(context)
                .load(originalImageFile)
                .ignoreBy(90)
                .setTargetDir(tempDir.getAbsolutePath())
                .putGear(4)
                .setCompressListener(listener)// You can choose different compression levels
                .launch();

    }

    /**
     * Copies the content from one file to another.
     *
     * @param inStream  The input stream to read from.
     * @param outStream The output stream to write to.
     * @throws IOException If an I/O error occurs.
     */
    public void copyFile(FileInputStream inStream, FileOutputStream outStream) throws IOException {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, length);
        }
        inStream.close();
        outStream.close();
    }
}

